package com.tumanex.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.tumanex.R;
import com.tumanex.socialshare.ConstantsApp;
import com.tumanex.socialshare.SitesApp;

/**
 * 
 * @author artemka
 * 
 */
public class LoginActivity extends Activity {

	private WebView mWebView;

	private SitesApp app;

	private String chosenSocNet;

	private String chosenAuthUrl;

	private String chosenAuthRedirect;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		mWebView = (WebView) findViewById(R.id.authWebView);
		setWebSetting();

		app = new SitesApp(getApplicationContext());

		chosenSocNet = getIntent().getStringExtra("socnet");
		setSocNet();

		setResult(RESULT_CANCELED);

		mWebView.loadUrl(chosenAuthUrl);
	}

	class AuthWebClient extends WebViewClient {
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);

			parseUrl(url);
		}

	}

	private void setWebSetting() {
		if (mWebView != null) {
			mWebView.getSettings().setJavaScriptEnabled(true);
			mWebView.clearCache(true);
			mWebView.setWebViewClient(new AuthWebClient());
			CookieSyncManager.createInstance(this);
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.removeAllCookie();
		}
	}

	private void parseUrl(String url) {

		try {
			if (url == null)
				return;
			if (url.startsWith(chosenAuthRedirect)) {
				if (url.contains("error")) {
				} else {
					String[] auth = app.parseUrlParams(url);
					Intent intent = new Intent();
					intent.putExtra("token", auth);
					setResult(Activity.RESULT_OK, intent);
				}
				finish();
			}
		} catch (Exception e) {
		}

	}

	private void setSocNet() {

		if (chosenSocNet.equals("VKONTAKTE")) {

			chosenAuthRedirect = ConstantsApp.VK_REDIRECT_URL;
			chosenAuthUrl = ConstantsApp.VK_OAUTH_AUTHORIZE_URL;

		} else {

		}
	}
}
